# vowei.py - vowei integration for mercurial
#
# copyright 2010 Shi Yimin <yimin_shi@hotmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License versoin 2 or any later version
import urllib, urlparse, json, re, httplib
from mercurial.i18n import _
from mercurial.node import short
from mercurial import cmdutil, templater, util
import vowei_hook_common

class vowei(vowei_hook_common.vowei_hook_base):    
    def __init__(self, ui = None):
        self.ui = ui
        vowei_hook_common.vowei_hook_base.__init__(self)

    def read_config(self):
        if self._bug_re is None:
            if self.ui is None:
                self._bug_re = re.compile(vowei._default_bug_re,
                                           re.IGNORECASE)
            else:
                self._bug_re = re.compile(
                    self.ui.config('vowei', 'regexp', vowei._default_bug_re),
                    re.IGNORECASE)
            
        self.host = self.ui.config("vowei", "url", "www.vowei.com")
        self.path = self.ui.config("vowei", "path", "/Comment/PostComments")

    def configitems(self, section):
        return self.ui.configitems(section)

def hook(ui, repo, hooktype, node=None, **kwargs):
    if node is None:
        raise util.About(_('hook type %s does not pass a changeset id') %
                         hooktype)
    
    try:
        vw = vowei(ui)
        ctx = repo[node]
        message = ctx.description()        
        commiter = ctx.user()        
        ids = vw.find_work_item_ids(message)
        if ids:
            comments = vw.create_comments(ctx, node, ids)

            if ( len(comments) > 0 ):            
                vw.post_comments(comments, vw.host, vw.path)
    except Exception, err:
        raise util.Abort(_('network error: %s') % err.args[1])
